package pers.archives.common.utils.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import pers.archives.common.utils.BeanUtil;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/* redis 操作工具类
 *@program:archives-parent
 *@author: 赵浩浩
 *@Time: 2020/9/7  14:12
 */
@Slf4j
public class RedisUtil {

    private static RedisTemplate redisTemplate = (RedisTemplate) BeanUtil.getBean("redisTemplate");

    /* ----------- common --------- */
    public static Collection<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

    public static void delete(String key) {
        redisTemplate.delete(key);
    }

    public static void delete(Collection<String> key) {
        redisTemplate.delete(key);
    }

    public static boolean hasKey(String key) {
        return	redisTemplate.hasKey(key);
    }




    /**
     * get
     * @param key
     * @return
     */
    public static Object get(String key) {

        Object value = redisTemplate.opsForValue().get(key);
        if(value!=null) {
            byte[] val=(byte[]) value;
            value=SerializeUtil.unserialize(val);
        }
        return value;
    }




    /**
     *
     * @param key
     * @param obj
     */
    public static void set(String key, Object obj) {
        if (obj == null) {
            return;
        }
        redisTemplate.opsForValue().set(key, SerializeUtil.serialize(obj));
    }


    /**
     * getString
     * @param key
     * @return
     */
    public static String getString(String key){
        Object value = redisTemplate.opsForValue().get( key);
        String valueRetun = "";

        if(value!=null) {
            byte[] val=(byte[]) value;
            valueRetun=SerializeUtil.unserialize(val).toString();
        }
        return valueRetun;
    }

    /**
     * set key time
     * @param key 键
     * @param obj 值
     * @param timeout 超时时间
     * @param unit  超时时间单位 参照TimeUnit
     */
    public static void setKeyByTime(String key, Object obj, Long timeout, TimeUnit unit) {
        if (obj == null) {
            return;
        }

        if (timeout != null) {
            redisTemplate.opsForValue().set( key, SerializeUtil.serialize(obj), timeout, unit);
        } else {
            redisTemplate.opsForValue().set(key, SerializeUtil.serialize(obj));
        }
    }

}
